<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <div class="search-container">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true">
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="queryParams.mobile" placeholder="请输入手机号" clearable style="width: 200px"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="queryParams.content" placeholder="请输入投诉内容关键词" clearable style="width: 200px"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="创建时间" prop="dateRange">
          <el-date-picker v-model="queryParams.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" style="width: 240px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">
            搜索
          </el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 操作按钮 -->
    <div class="toolbar">
      <div></div>
      <div class="toolbar-right">
        <el-button :icon="Refresh" @click="handleRefresh">刷新</el-button>
      </div>
    </div>
    <!-- 投诉表格 -->
    <el-table v-loading="loading" :data="complaintList" border stripe>
      <el-table-column label="ID" prop="id" width="80" align="center" />
      <el-table-column label="手机号" prop="mobile" align="center" />
      <el-table-column label="投诉内容" prop="content" min-width="400" show-overflow-tooltip>
        <template #default="{ row }">
          <div class="content-cell">
            {{ row.content }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="附件" prop="attachments" align="center">
        <template #default="{ row }">
          <div v-if="row.attachments && row.attachments.length > 0">
            <div v-for="(file, index) in row.attachments" :key="index" class="attachment-btn">
              <el-icon>
                <Document />
              </el-icon>
              {{ file.name }}
            </div>
          </div>
          <span v-else class="no-attachment">无附件</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" align="center" />
      <el-table-column label="操作" width="200" align="center" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" :icon="View" @click="handleView(row)">
            查看
          </el-button>

          <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize" :total="total"
        :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" @size-change="handleQuery"
        @current-change="handleQuery" />
    </div>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="投诉详情" width="600px">
      <div class="detail-container" v-if="currentComplaint">
        <div class="detail-item">
          <label>手机号：</label>
          <span>{{ currentComplaint.mobile }}</span>
        </div>
        <div class="detail-item">
          <label>创建时间：</label>
          <span>{{ currentComplaint.createTime }}</span>
        </div>
        <div class="detail-item">
          <label>投诉内容：</label>
          <div class="content-detail">
            {{ currentComplaint.content }}
          </div>
        </div>
        <div class="detail-item" v-if="
          currentComplaint.attachments &&
          currentComplaint.attachments.length > 0
        ">
          <label>附件：</label>
          <div class="attachments-detail">
            <div class="image-gallery">
              <div v-for="(file, index) in currentComplaint.attachments" :key="index" class="image-item"
                @click="handleImagePreview(file, index)">
                <el-image :src="file.url" :alt="file.name" fit="cover" class="preview-image"
                  :preview-src-list="getImageUrls(currentComplaint.attachments)" :initial-index="index"
                  preview-teleported>
                  <template #error>
                    <div class="image-error">
                      <el-icon>
                        <Picture />
                      </el-icon>
                      <span>{{ file.name }}</span>
                    </div>
                  </template>
                </el-image>
                <div class="image-name">{{ file.name }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Search,
  Refresh,
  Plus,
  Delete,
  Edit,
  View,
  Document,
  UploadFilled,
  Picture,
} from "@element-plus/icons-vue";
import type { UploadFile, UploadFiles } from "element-plus";

defineOptions({
  name: "Complaint",
});

// 响应式数据
const loading = ref(false);
const submitLoading = ref(false);
const dialogVisible = ref(false);
const viewDialogVisible = ref(false);
const isEdit = ref(false);
const total = ref(0);
const complaintList = ref<ComplaintItem[]>([]);
const currentComplaint = ref<ComplaintItem | null>(null);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  mobile: "",
  content: "",
  dateRange: [],
});

// 投诉表单
const complaintForm = reactive({
  id: undefined,
  mobile: "",
  content: "",
  attachments: [] as UploadFile[],
});

// 表单验证规则
const complaintRules = {
  mobile: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号格式",
      trigger: "blur",
    },
  ],
  content: [
    { required: true, message: "请输入投诉内容", trigger: "blur" },
    {
      min: 10,
      max: 500,
      message: "投诉内容长度在 10 到 500 个字符",
      trigger: "blur",
    },
  ],
};

// 计算属性
const dialogTitle = computed(() => (isEdit.value ? "编辑投诉" : "新增投诉"));

// 引用
const queryFormRef = ref();
const complaintFormRef = ref();
const uploadRef = ref();

// 投诉数据类型
interface ComplaintItem {
  id: number;
  mobile: string;
  content: string;
  attachments?: {
    name: string;
    url: string;
    size: number;
  }[];
  createTime: string;
}

// 查询投诉列表
const getComplaintList = async () => {
  loading.value = true;
  try {
    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 500));

    // 模拟数据
    // const mockData = [
    //   {
    //     id: 1,
    //     mobile: "13800138000",
    //     content: "服务态度不好，工作人员很不耐烦，希望能够改进服务质量。",
    //     attachments: [
    //       {
    //         name: "投诉截图.jpg",
    //         url: "/files/complaint1.jpg",
    //         size: 1024000,
    //       },
    //     ],
    //     createTime: "2024-01-15 10:30:00",
    //   },
    //   {
    //     id: 2,
    //     mobile: "13800138001",
    //     content: "产品质量有问题，使用不到一周就出现故障，要求退换货。",
    //     attachments: [
    //       {
    //         name: "产品照片.jpg",
    //         url: "/files/product1.jpg",
    //         size: 2048000,
    //       },
    //       {
    //         name: "购买凭证.pdf",
    //         url: "/files/receipt1.pdf",
    //         size: 512000,
    //       },
    //     ],
    //     createTime: "2024-01-14 14:20:00",
    //   },
    //   {
    //     id: 3,
    //     mobile: "13800138002",
    //     content: "配送延迟，承诺3天到货，结果一周都没有收到商品。",
    //     attachments: [],
    //     createTime: "2024-01-13 09:15:00",
    //   },
    // ];

    // complaintList.value = mockData;
    // total.value = mockData.length;
  } catch (error) {
    ElMessage.error("获取投诉列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleQuery = () => {
  queryParams.pageNum = 1;
  getComplaintList();
};

// 重置搜索
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

// 刷新
const handleRefresh = () => {
  getComplaintList();
};

// 新增投诉
const handleAdd = () => {
  isEdit.value = false;
  dialogVisible.value = true;
  resetComplaintForm();
};

// 编辑投诉
const handleEdit = (row: ComplaintItem) => {
  isEdit.value = true;
  dialogVisible.value = true;
  Object.assign(complaintForm, {
    id: row.id,
    mobile: row.mobile,
    content: row.content,
    attachments:
      row.attachments?.map((file) => ({
        name: file.name,
        url: file.url,
        status: "success",
      })) || [],
  });
};

// 查看详情
const handleView = (row: ComplaintItem) => {
  currentComplaint.value = row;
  viewDialogVisible.value = true;
};

// 删除投诉
const handleDelete = async (row: ComplaintItem) => {
  try {
    await ElMessageBox.confirm(`确定要删除这条投诉记录吗？`, "删除确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    // 模拟删除API调用
    await new Promise((resolve) => setTimeout(resolve, 500));

    ElMessage.success("删除成功");
    getComplaintList();
  } catch (error) {
    // 用户取消删除
  }
};

// 文件上传相关
const handleFileChange = (file: UploadFile, fileList: UploadFiles) => {
  complaintForm.attachments = fileList;
};

const handleFileRemove = (file: UploadFile, fileList: UploadFiles) => {
  complaintForm.attachments = fileList;
};

const beforeUpload = (file: File) => {
  const isValidType = [
    "image/jpeg",
    "image/png",
    "application/pdf",
    "application/msword",
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  ].includes(file.type);

  const isLt10M = file.size / 1024 / 1024 < 10;

  if (!isValidType) {
    ElMessage.error("只能上传 JPG/PNG/PDF/DOC/DOCX 格式的文件!");
    return false;
  }
  if (!isLt10M) {
    ElMessage.error("上传文件大小不能超过 10MB!");
    return false;
  }
  return false; // 阻止自动上传
};

// 下载附件
const handleDownload = (file: any) => {
  // 模拟下载
  const link = document.createElement("a");
  link.href = file.url;
  link.download = file.name;
  link.click();
  ElMessage.success(`开始下载 ${file.name}`);
};

// 提交表单
const handleSubmit = async () => {
  try {
    await complaintFormRef.value?.validate();

    submitLoading.value = true;

    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 1000));

    ElMessage.success(isEdit.value ? "更新成功" : "新增成功");
    dialogVisible.value = false;
    getComplaintList();
  } catch (error) {
    console.error("表单验证失败:", error);
  } finally {
    submitLoading.value = false;
  }
};

// 对话框关闭
const handleDialogClose = () => {
  complaintFormRef.value?.resetFields();
  resetComplaintForm();
};

// 重置投诉表单
const resetComplaintForm = () => {
  Object.assign(complaintForm, {
    id: undefined,
    mobile: "",
    content: "",
    attachments: [],
  });
};

// 页面加载时获取数据
onMounted(() => {
  getComplaintList();
});

// 获取图片URL列表
const getImageUrls = (attachments: any[]) => {
  return attachments?.map((file) => file.url) || [];
};

// 图片预览处理
const handleImagePreview = (file: any, index: number) => {
  // 这里可以添加额外的预览逻辑，如果需要的话
  console.log("预览图片:", file.name);
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.search-container {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  .toolbar-left,
  .toolbar-right {
    display: flex;
    gap: 10px;
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}

.content-cell {
  max-width: 400px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.attachment-btn {
  display: block;
  margin-bottom: 5px;
  padding: 2px 0;

  .el-icon {
    margin-right: 4px;
  }
}

.no-attachment {
  color: #999;
  font-style: italic;
}

.detail-container {
  .detail-item {
    margin-bottom: 20px;

    label {
      font-weight: bold;
      color: #333;
      margin-right: 10px;
      min-width: 80px;
      display: inline-block;
    }

    .content-detail {
      margin-top: 8px;
      padding: 10px;
      background-color: #f5f7fa;
      border-radius: 4px;
      line-height: 1.6;
      white-space: pre-wrap;
    }

    .attachments-detail {
      margin-top: 8px;

      .image-gallery {
        display: flex;
        flex-wrap: wrap;
        gap: 12px;

        .image-item {
          position: relative;
          cursor: pointer;
          border-radius: 8px;
          overflow: hidden;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
          transition:
            transform 0.2s,
            box-shadow 0.2s;

          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
          }

          .preview-image {
            width: 120px;
            height: 120px;
            border-radius: 8px;

            .image-error {
              display: flex;
              flex-direction: column;
              align-items: center;
              justify-content: center;
              height: 100%;
              background-color: #f5f7fa;
              color: #909399;
              font-size: 12px;

              .el-icon {
                font-size: 24px;
                margin-bottom: 8px;
              }

              span {
                text-align: center;
                word-break: break-all;
                padding: 0 8px;
              }
            }
          }

          .image-name {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
            color: white;
            padding: 8px 6px 4px;
            font-size: 12px;
            text-align: center;
            word-break: break-all;
            line-height: 1.2;
          }
        }
      }
    }
  }
}

// 表格样式优化
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;

  .el-table__header {
    background-color: #f8f9fa;
  }
}

// 上传组件样式
:deep(.el-upload-dragger) {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  width: 100%;
  height: 120px;
  text-align: center;
  background-color: #fafafa;
  transition: border-color 0.3s;

  &:hover {
    border-color: #409eff;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    gap: 10px;

    .toolbar-left,
    .toolbar-right {
      width: 100%;
      justify-content: center;
    }
  }

  .search-container {
    :deep(.el-form--inline) {
      .el-form-item {
        display: block;
        margin-bottom: 10px;

        .el-form-item__content {
          margin-left: 0 !important;
        }
      }
    }
  }
}
</style>
